package com.zh.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.exception.BusinessException;
import com.zh.system.domain.dto.AddMsgTemplateDto;
import com.zh.system.domain.dto.PageTemplateDto;
import com.zh.system.domain.dto.UpdateMessageTemplateDto;
import com.zh.system.domain.entity.SysMsgTemplate;
import com.zh.system.mapper.SysMsgTemplateMapper;
import com.zh.system.service.SysMessageTemplateService;
import com.zh.web.base.PageApiResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysMessageTemplateServiceImpl extends ServiceImpl<SysMsgTemplateMapper, SysMsgTemplate> implements SysMessageTemplateService {


    private final SysMsgTemplateMapper sysMsgTemplateMapper;
    @Override
    public String addTemplate(AddMsgTemplateDto addMsgTemplateDto) {
        String[] keywords = addMsgTemplateDto.getKeywords();
        if (keywords == null || keywords.length == 0) {
            throw new BusinessException("关键词不能为空");
        }
        String template = addMsgTemplateDto.getTemplate();
        if (StrUtil.isEmpty(template)) {
            throw new BusinessException("模板不能为空");
        }
        SysMessageTemplateServiceImpl proxy = (SysMessageTemplateServiceImpl) AopContext.currentProxy();
        SysMsgTemplate sysMsgTemplate = BeanUtil.copyProperties(addMsgTemplateDto, SysMsgTemplate.class);
        sysMsgTemplate.toKeyword();
        boolean saved = proxy.save(sysMsgTemplate);
        if (saved) {
            return "添加成功";
        } else {
            throw new BusinessException("添加失败");
        }
    }

    @Override
    public SysMsgTemplate getTemplateById(Long id) {
        SysMessageTemplateServiceImpl proxy = (SysMessageTemplateServiceImpl) AopContext.currentProxy();
        SysMsgTemplate template = proxy.getById(id);
        template.toKeywords();
        return template;
    }

    @Override
    public String updateTemplate(UpdateMessageTemplateDto updateMessageTemplateDto) {
        SysMessageTemplateServiceImpl proxy = (SysMessageTemplateServiceImpl) AopContext.currentProxy();
        SysMsgTemplate oldTemplate = proxy.getById(updateMessageTemplateDto.getId());
        oldTemplate.toKeywords();
        SysMsgTemplate sysMsgTemplate = BeanUtil.copyProperties(updateMessageTemplateDto, SysMsgTemplate.class);
        sysMsgTemplate.toKeyword();
        //修改模板时 不改关键词 检测关键词前后是否一致
        if (StrUtil.isNotEmpty(sysMsgTemplate.getTemplate()) && ArrayUtil.isEmpty(sysMsgTemplate.getKeywords())) {
            String[] keywords = this.parseKeywords(sysMsgTemplate.getTemplate());
            boolean equals = ArrayUtil.equals(keywords, oldTemplate.getKeywords());
            if (!equals) {
                throw new BusinessException("模板内容与关键词不匹配");
            }
        }
        //不修改模板内容,不允许修改关键词
        if (StrUtil.isEmpty(sysMsgTemplate.getTemplate()) && StrUtil.isNotEmpty(sysMsgTemplate.getKeyword())) {
            throw new BusinessException("拒绝单独修改关键词");
        }
        //同时修改模板内容,关键词,检测关键词是否一致
        if (StrUtil.isNotEmpty(sysMsgTemplate.getTemplate()) && ArrayUtil.isNotEmpty(sysMsgTemplate.getKeywords())) {
            String[] keywords = this.parseKeywords(sysMsgTemplate.getTemplate());
            boolean equals = ArrayUtil.equals(keywords, sysMsgTemplate.getKeywords());
            if (!equals) {
                throw new BusinessException("模板内容与关键词不匹配");
            }
        }
        LambdaUpdateWrapper<SysMsgTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysMsgTemplate::getId, sysMsgTemplate.getId());
        updateWrapper.set(StrUtil.isNotEmpty(sysMsgTemplate.getName()), SysMsgTemplate::getName, sysMsgTemplate.getName());
        updateWrapper.set(StrUtil.isNotEmpty(sysMsgTemplate.getType()), SysMsgTemplate::getType, sysMsgTemplate.getType());
        updateWrapper.set(StrUtil.isNotEmpty(sysMsgTemplate.getSource()), SysMsgTemplate::getSource, sysMsgTemplate.getSource());
        updateWrapper.set(StrUtil.isNotEmpty(sysMsgTemplate.getKeyword()), SysMsgTemplate::getKeyword, sysMsgTemplate.getKeyword());
        updateWrapper.set(StrUtil.isNotEmpty(sysMsgTemplate.getTemplate()), SysMsgTemplate::getTemplate, sysMsgTemplate.getTemplate());
        updateWrapper.set(sysMsgTemplate.getStatus() != null, SysMsgTemplate::getStatus, sysMsgTemplate.getStatus());
        boolean updated = proxy.update(updateWrapper);
        if (updated) {
            return "修改成功";
        } else {
            throw new BusinessException("修改失败");
        }
    }

    @Override
    public String deleteTemplate(Long id) {
        SysMessageTemplateServiceImpl proxy = (SysMessageTemplateServiceImpl) AopContext.currentProxy();
        boolean deleted = proxy.removeById(id);
        if (deleted) {
            return "删除成功";
        } else {
            throw new BusinessException("删除失败");
        }
    }

    @Override
    public PageApiResult<SysMsgTemplate> pageTemplate(PageTemplateDto pageTemplateDto) {
        pageTemplateDto.setPageNum(pageTemplateDto.getPageNum() < 1L ? 1L : pageTemplateDto.getPageNum());
        pageTemplateDto.setPageSize(pageTemplateDto.getPageSize() < 1L ? 10L : pageTemplateDto.getPageSize());
        Page<SysMsgTemplate> page = new Page<>(pageTemplateDto.getPageNum(), pageTemplateDto.getPageSize());
        List<SysMsgTemplate> sysMsgTemplateList = sysMsgTemplateMapper.page(page, pageTemplateDto);
        page.setRecords(sysMsgTemplateList);
        return PageApiResult.<SysMsgTemplate>builder()
                .pageNum(page.getCurrent())
                .pageSize(page.getSize())
                .total(page.getTotal())
                .list(page.getRecords())
                .build();
    }

    // 2024/11/4 解析模板内容，获取模板中的关键词
    private String[] parseKeywords(String content) {
        if (StrUtil.isNotEmpty(content)) {
            List<String> keywords = new java.util.ArrayList<>();
            String regex = "\\$\\{(.*?)\\}";
            Pattern pattern = java.util.regex.Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                keywords.add(matcher.group(1));
            }
            return keywords.toArray(new String[0]);
        } else {
            return new String[0];
        }
    }
}
